package com.wingsboat;


import com.wingsboat.interfaces.Filter;
import com.wingsboat.interfaces.FilterChain;
import com.wingsboat.interfaces.FilterContext;
import com.wingsboat.interfaces.Pipeline;
import com.wingsboat.sort.FilterChainMergeSort;
import com.wingsboat.sort.FilterChainSort;

/**
 * 管道默认实现
 *
 * @author wangzhong
 */
public class DefaultPipeline<T extends FilterContext> implements Pipeline<T> {

    private FilterChain firstNode;

    /**
     * 获取链表头
     *
     * @return
     */
    @Override
    public FilterChain getFilterChain() {
        return firstNode;
    }

    /**
     * 开始过滤
     *
     * @param filterContext
     */
    @Override
    public void bootstrap(T filterContext) {
        FilterChainSort filterChainSort = new FilterChainMergeSort();
        firstNode = filterChainSort.sort(firstNode);
        firstNode.handle(filterContext);
    }

    /**
     * 增加过滤器
     *
     * @param filter
     * @return
     */
    @Override
    public Pipeline addFilter(Filter filter) {
        FilterChain filterChain = new DefaultFilterChain(filter,firstNode);
        firstNode = filterChain;
        return this;
    }
}
